package main

import (
	"fmt"
	"net/http"

	"github.com/gorilla/websocket"
)

var UP = websocket.Upgrader{
	ReadBufferSize:  1024,
	WriteBufferSize: 1024,
}

var conns []*websocket.Conn

func handler(w http.ResponseWriter, r *http.Request) {
	// 升级服务为websocket
	conn, err := UP.Upgrade(w, r, nil)
	defer conn.Close()
	if err != nil {
		fmt.Println(err.Error())
		return
	}
	// 存入所有的链接
	conns = append(conns, conn)
	// 链接没有断，读取数据
	for {
		m, p, e := conn.ReadMessage()
		if e != nil {
			fmt.Println(e.Error())
			break
		}
		fmt.Println(m, string(p))
		writerStr := "你说的是:" + string(p) + "嘛？"
		for _, v := range conns {
			v.WriteMessage(websocket.TextMessage, []byte(writerStr))
		}
		// conn.WriteMessage(websocket.TextMessage, []byte(writerStr))
		fmt.Println(writerStr)
	}
	fmt.Println("链接断开...")
}

func main() {
	http.HandleFunc("/", handler)
	fmt.Println("server start :8888")
	http.ListenAndServe(":8888", nil)
}
